package zhouyandong.exam.com.touch;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Administrator on 2016/12/1.
 */

public class TouchView extends View implements GestureDetector.OnGestureListener {


    private Matrix matrix;
    private Bitmap bitmap;
    private float lastDis;

    public TouchView(Context context) {
        this(context,null);

    }

    public TouchView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public TouchView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
        matrix = new Matrix();
        new GestureDetector(context,this);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap,matrix,null);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getPointerCount()==2) {
            float x1 = event.getX(0);
            float x2 = event.getX(1);
            float y1 = event.getY(0);
            float y2 = event.getY(1);
            float cx = (x1+x2)/2;
            float cy = (y1+y2)/2;
            float dis = (float) Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
            switch (event.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                    lastDis = dis;
//                    break;
                case MotionEvent.ACTION_MOVE:
                    matrix.postScale(dis/lastDis,dis/lastDis,cx,cy);
                    lastDis = dis;
                    break;
            }
        }
        invalidate();
        return true;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }
}
